package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-19
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {

    @Autowired
    private IApBehaviorEntryService entryService;
    //点赞取消点赞
    @Override
    public ResponseResult likeBehavior(LikesBehaviorDto dto) {
        ////通过线程查找用户
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存实体
        EntryDto entryDto = new EntryDto();
        entryDto.setUserId(user.getUserId());
        entryDto.setEquipmentId(dto.getEquipmentId());
        ApBehaviorEntry entry = entryService.getEntry(entryDto);
        //保存app的点赞行为表
        LambdaQueryWrapper<ApLikesBehavior> wapper=new LambdaQueryWrapper<>();
        wapper.eq(ApLikesBehavior::getArticleId, dto.getArticleId());
        wapper.eq(ApLikesBehavior::getEntryId, entry.getId());
        wapper.eq(ApLikesBehavior::getType, dto.getType());
        ApLikesBehavior behavior = this.getOne(wapper);

        if (behavior!= null) {
            behavior.setOperation(dto.getOperation());
        } else {
            behavior = new ApLikesBehavior();
            behavior.setOperation(dto.getOperation());
            behavior.setArticleId(Long.parseLong(dto.getArticleId()));
            behavior.setEntryId(entry.getId());
            behavior.setCreatedTime(new Date());
            behavior.setType(dto.getType());
        }
        saveOrUpdate(behavior);
        //同步到文章表
        //TODO
        return ResponseResult.okResult();
    }
}
